import React from 'react';
import './information.less';
import { hashHistory } from 'react-router';
import { Breadcrumb, Form, Modal, Input, Upload,  Icon,  Button, TreeSelect, message } from 'antd';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
import $ from 'jquery';
import Config from '../../common/config';
import draftToHtml from 'draftjs-to-html';
import { Editor } from 'react-draft-wysiwyg';
import '../../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

const FormItem = Form.Item;
const config = new Config();
const token = sessionStorage.getItem('token');
class information extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
      previewVisible: false,
      previewImage: '',
      operation: this.props.params.state, // 操作 add:新增 update:修改
      editorState: EditorState.createEmpty(),
      detail: {}, // 修改详情
    }
  }

  componentDidMount() {
    const operation = this.props.params.state
    if (operation === 'update') {
      const detail = this.props.location.state.data
      const html = ContentState.createFromBlockArray(htmlToDraft(detail.content || '<p></p>'))
      const editorState = EditorState.createWithContent(html)
      const { fileList } = this.state;
      fileList.push({
        uid: -1,
        name: detail.titleImage,
        status: 'done',
        url: config.Filepath + detail.titleImage,
      });

      this.props.form.setFieldsValue({
        title: detail.title,
        titleImage: fileList,
        label: detail.label,
        abstract: detail.abstract,
        classification: detail.classification
      })
      this.setState({
        fileList,
        detail,
        editorState
      })
    }
    $('.rdw-image-wrapper .rdw-option-wrapper').click(
      (e) => {
        $('#xFile').trigger('click');
        $('.rdw-image-modal').focus();
      }
    );
  }

  //富文本编辑器编辑改变内容函数
  onEditorStateChange(editorState) {
    this.setState({ editorState })
  }
  //关闭预览图片对话框
  cancelPreview() {
    this.setState({ previewVisible: false })
  }
  //富文本编辑器图片上传
  upload(e) {
    const formData = new FormData(); //创建一个form表单对象
    formData.append('img', e.target.files[0]); //表单对象压入图片
    if (e.target.files.length) {

      const xhr = new XMLHttpRequest();
      xhr.open('POST', config.UploadFile + '/websitNewsImg');
      xhr.send(formData);
      xhr.addEventListener('load', () => {
        const response = JSON.parse(xhr.responseText);
        console.log(xhr.responseText, response)
        if (response.code == 200) {
          this.setState({
            imageFile: response.data
          }, () => {
            $('.rdw-image-modal-url-input')[0].value = config.Filepath + response.data;
            $('.rdw-image-modal-size .rdw-image-modal-size-input')[1].value = '100%';
            $('.rdw-image-modal-url-input').focus();
            $('.rdw-image-modal-url-input').blur();
          });
        }
      });
      xhr.addEventListener('error', () => {
        const error = JSON.parse(xhr.responseText);
      });
    }
  }
  //编辑器预览功能
  previewEditor(key) {
    //key=0 为说明书预览，key=1为介绍预览
    let html = '';
    if (key == 0) {
      html = draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()));
    } else {
      html = draftToHtml(convertToRaw(this.state.editorIntro.getCurrentContent()));
    }
    this.setState({
      visible: true,
    }, () => {
      $('#preview').html(html)
    })

  }
  //隐藏预览模态框
  hideModal() {
    this.setState({
      visible: false,
    })
  }
  //预览图片对话框
  previewImg(file) {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  //限制用户必须上传图片格式的文件、图片大小
  beforeUpload(file, fileList) {
    let isIMG = file.type.indexOf('image') != -1;
    if (!isIMG) {
      message.config({ top: 50 });
      message.error('您只能上传图片！');
    }
    let isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.config({ top: 50 });
      message.error('您上传的图片大小必须小于10MB！');
    }
    return isIMG && isLt10M;
  }
  // 新增或修改
  save(e) {
    const content = draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let url = `${config.jusewebsite_zml}/news`
        const data = {
          title: values.title,
          titleImage: values.titleImage[0].response ? values.titleImage[0].response.data : values.titleImage[0].name,
          label: values.label,
          abstract: values.abstract,
          classification: values.classification,
          content
        }
        console.log('1:  ', data)
        console.log('2:  ', values)
        if (this.state.operation === 'add') {
          url += '/add'
        } else {
          url += '/update'
          data.id = this.state.detail.id
        }
        $.ajax({
          url,
          type: 'post',
          data,
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          success: res => {
            console.log('操作新闻', res)
            if (res.code === 200) {
              message.success(res.mes)
              this.linkPrev()
            }
          }
        })
      }
    })
  }

  // 跳转上一个页面
  linkPrev() {
    if (this.state.operation === 'add') {
      hashHistory.push({ pathname: '/informationList_zml' })
    } else {
      const paths = {
        pathname: '/informationList_zml',
        state: this.props.location.state
      };
      hashHistory.push(paths);
    }
  }
  //上传图片
  normFile(e) {
    console.log(e)
    this.setState({
      fileList: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    const { fileList } = this.state;
    const formItemLayout = { labelCol: { span: 3 }, wrapperCol: { span: 21 } };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 3,
        },
      },
    };

    const treeData = [
      {
        label: '品牌动态',
        value: '品牌动态',
        key: '0-0',
        children: [],
      },
      {
        label: '行业新闻',
        value: '行业新闻',
        key: '0-1',
        children: [],
      },
      {
        label: '瘦身百科',
        value: '瘦身百科',
        key: '0-2',
        children: [],
      }
    ];

    return (
      <div className='contentBox clearfix'>
        <div className="member-content-Search">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>官网管理</Breadcrumb.Item>
              {
                this.state.operation === 'add'
                  ?
                  <Breadcrumb.Item>新增</Breadcrumb.Item>
                  :
                  <Breadcrumb.Item>修改</Breadcrumb.Item>
              }
            </Breadcrumb>
            <div style={{ width: '50%', marginTop: 50 }}>
              <Form onSubmit={this.save.bind(this)}>
                <FormItem
                  {...formItemLayout}
                  label="标题"
                  hasFeedback
                >
                  {getFieldDecorator('title', {
                    rules: [{
                      required: true, message: '请填写标题!',
                    }],
                  })(
                    <Input type="title" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="标题图片"
                  hasFeedback
                >
                  {getFieldDecorator('titleImage', {
                    valuePropName: 'fileList', getValueFromEvent: this.normFile.bind(this),
                    rules: [{
                      required: true, message: '请上传标题图片!',
                    }],
                  })(
                    <Upload
                      accept="image/*"
                      name="img"
                      action={config.UploadFile + "/websitNewsImg"}
                      beforeUpload={this.beforeUpload.bind(this)}
                      listType="picture-card"
                      className="upload-list-inline"
                      style={{ float: 'left' }}
                      onPreview={this.previewImg.bind(this)}
                    >
                      {
                        fileList.length >= 1 ? null :
                          <div>
                            <Icon type="plus" />
                            <div className="ant-upload-text">点击上传图片</div>
                          </div>
                      }
                    </Upload>
                  )}
                </FormItem>
                <Modal visible={this.state.previewVisible} footer={null} onCancel={this.cancelPreview.bind(this)}>
                  <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
                <FormItem
                  {...formItemLayout}
                  label="标签"
                  hasFeedback
                >
                  {getFieldDecorator('label', {
                    rules: [{
                      required: true, message: '请填写标签!',
                    }],
                  })(
                    <Input type="label" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="摘要"
                  hasFeedback
                >
                  {getFieldDecorator('abstract', {
                    rules: [{
                      required: true, message: '请填写摘要!',
                    }],
                  })(
                    <Input type="abstract" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="分类"
                  hasFeedback
                >
                  {getFieldDecorator('classification', {
                    rules: [{
                      required: true, message: '请选择分类!',
                    }],
                  })(
                    <TreeSelect
                      setFieldsValue={this.state.value}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={treeData}
                      placeholder='请选择分类'
                      treeDefaultExpandAll
                    />
                  )}
                </FormItem>
                <FormItem
                  label="内容编辑"
                  hasFeedback
                  {...formItemLayout}
                >
                  <div className="goodsdetail-form" style={{ width: '100%', }}>
                    <Editor
                      editorState={this.state.editorState}
                      wrapperClassName="demo-wrapper"
                      editorClassName="demo-editor"
                      onEditorStateChange={this.onEditorStateChange.bind(this)}
                      toolbar={{
                        //inline: { inDropdown: true },
                        //list: { inDropdown: true },
                        textAlign: { inDropdown: true },
                        link: { inDropdown: true },
                        image: {
                          //uploadCallback: this.upload.bind(this),
                          //     alt: { present: true, mandatory: true }
                          defaultSize: {
                            height: 'auto',
                            width: '100%',
                          },
                        }
                      }}
                      localization={{
                        locale: 'zh'
                      }}
                    />
                    <input
                      type="file"
                      id="xFile"
                      name="xFile"
                      style={{ position: 'absolute', opacity: 0, display: 'none' }}
                      onChange={this.upload.bind(this)}
                    />
                  </div>
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                  <Button type="primary" htmlType="submit" size="small" style={{ width: '100px', height: '35px' }}>确定</Button> <Button style={{ width: '100px', height: '35px' }} size="small" onClick={this.linkPrev.bind(this)}>取消</Button>
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(information);
